package com.jplus.core.plugin.scheduling;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.anno.boot.Configuration;
import com.jplus.core.anno.com.Autowired;
import com.jplus.core.anno.com.Order;
import com.jplus.core.core.ApplicationContext;

@Configuration
@Order(Integer.MAX_VALUE)
public class SchedulingConfiguration {
	private final Logger log = LoggerFactory.getLogger(SchedulingConfiguration.class);

	@Autowired
	private ApplicationContext context;

	@PostConstruct
	public void startScheduling() {
		List<ScheduTask> list = SchedulingConfigurationSelector.getListScheduTask();
		for (ScheduTask task : list) {
			Thread t = new ScheduThread(task, context);
			t.setDaemon(true);
			t.setName(task.getName());
			t.start();
			log.info("[SchedulingThread] start:" + task.getName());
		}
	}

	public class ScheduThread extends Thread {
		private final ScheduTask task;
		private final ApplicationContext context;

		public ScheduThread(ScheduTask task, ApplicationContext context) {
			this.task = task;
			this.context = context;
			task.start();
		}

		@Override
		public void run() {
			while (context.isRuning()) {
				try {
					Date now = new Date();
					Date next = task.nextTime(now);
					if (next.after(now)) {
						log.info("[Task]:Next execution time = " + next);
						long time = next.getTime() - now.getTime();
						Thread.sleep(time);
						Object obj = context.getBean(task.getBeanKey());
						task.getMethod().invoke(obj, new Object[] {});// 执行任务
						task.isDelayOver();
					} else {
						Thread.sleep(1000);
					}
				} catch (Exception e) {
					log.error("ScheduThread ERROR:", e);
				}
			}
		}

	}

}
